/*
 * Copyright 2012-2014 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.jqd.framework.core.hessian.biz.action.support.annotation;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;

import com.jqd.framework.core.hessian.biz.action.support.AbstractActionHandlerMapping;
import com.jqd.framework.core.hessian.model.ServiceRequest;

/**
 * 
 * TODO
 * 
 * @author liaozhicheng.cn@gmail.com
 * @date 2012-6-11
 * @since 1.0
 */
public class AnnotationActionHandlerMapping extends AbstractActionHandlerMapping {
	
	@Override
	protected Object getHandlerInternal(ServiceRequest serviceRequest) {
		return null;
	}
	
	
	@Override
	protected void initAllHandleMapping(ApplicationContext applicationContext) {
		
		Map<String, Object> matchBeans = applicationContext
				.getBeansWithAnnotation(ActionHandler.class);
		if (!matchBeans.isEmpty()) {
			Map<String, Object> handleMap = new HashMap<String, Object>();
			
			for (Object handler : matchBeans.values()) {
				for (Method handleMethod : findHandleMethods(handler)) {
					HandleRquest hr = handleMethod.getAnnotation(HandleRquest.class);
					if (StringUtils.isNotEmpty(hr.value())) {
						handleMap.put(hr.value(), handler);
						
						logInfo(hr.value(), handler);
					}
				}
			}
			registerHandler(handleMap);
		}
	}
	
	
	/**
	 * 通过反射找到某个具体的Action（即handler）中所有有效的action方法
	 * 
	 * @param handler
	 *            具体的Action对象
	 * @return
	 */
	private List<Method> findHandleMethods(Object handler) {
		
		List<Method> matchMethods = new ArrayList<Method>();
		
		// 获取该类及父类中所有方法，不包括私有方法
		Method[] handlerMethods = handler.getClass().getMethods();
		for (Method handlerMethod : handlerMethods) {
			if (isAnnotationHandlerMethod(handlerMethod)) {
				matchMethods.add(handlerMethod);
			}
		}
		return matchMethods;
	}
	
	
	private boolean isAnnotationHandlerMethod(Method handleMethod) {
		
		if (isHandlerMethod(handleMethod)) {
			return handleMethod.isAnnotationPresent(HandleRquest.class);
		}
		return false;
	}
	
}
